<?php
/**
 * PddGoodsCatTemplateDao.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2021/1/17- 下午4:20
 */

namespace common\jobs\dao;


use common\exception\ValidatorException;
use common\library\BaseDao;
use common\models\pdd\PddGoodsCatTemplate;

class PddGoodsCatTemplateDao extends BaseDao
{
    /**
     * 写入信息
     * @param array $data
     * @return PddGoodsCatTemplate
     * @throws ValidatorException
     */
    public function insertData(array $data)
    {
        $catTemplate = new PddGoodsCatTemplate();

        $catTemplate->load($data,'');

        if (!$catTemplate->validate()) {
            throw new ValidatorException($catTemplate->errorsToString());
        }

        if($catTemplate->save())
        {
            return $catTemplate;
        }else{
            throw new ValidatorException($catTemplate->errorsToOneString());
        }
    }

    /**
     * 存在写入 不存在更新
     * @param array $data
     * @return PddGoodsCatTemplate|null
     * @throws ValidatorException
     */
    public function insertOrUpdateData(array $data)
    {
        if(!isset($data['id'])) throw new ValidatorException('参数缺失');

        $catTemplate = new PddGoodsCatTemplate();

        $catTemplateSet = PddGoodsCatTemplate::findOne(['id'=>$data['id']]);
        /**
         * 存在更新操作
         */
        if($catTemplateSet)
        {
            $catTemplate = $catTemplateSet;
        }


        $catTemplate->load($data,'');

        if (!$catTemplate->validate()) {
            throw new ValidatorException($catTemplate->errorsToString());
        }

        if($catTemplate->save())
        {
            return $catTemplate;
        }else{
            throw new ValidatorException($catTemplate->errorsToOneString());
        }
    }


    /**
     * 更新
     * @param PddGoodsCatTemplate $catTemplate
     * @param array $data
     * @return PddGoodsCatTemplate
     * @throws ValidatorException
     */
    public function updateData(PddGoodsCatTemplate $catTemplate, array $data)
    {
        $catTemplate->load($data,'');

        if (!$catTemplate->validate()) {
            throw new ValidatorException($catTemplate->errorsToString());
        }

        if($catTemplate->save())
        {
            return $catTemplate;
        }else{

            throw new ValidatorException($catTemplate->errorsToOneString());
        }
    }


    /**
     * 通过主键获取信息
     * @param int $id
     * @return PddGoodsCatTemplate|null
     */
    public function getTemplateById(int $id)
    {
        return PddGoodsCatTemplate::findOne(['id'=>$id]);
    }


    /**
     * 通过cat_id 获取详细信息
     * @param int $cadId
     * @return PddGoodsCatTemplate|null
     */
    public function getTemplateByCid(int $cadId)
    {
        return PddGoodsCatTemplate::findOne(['cat_id'=>$cadId]);
    }
}